import axios from 'axios'
import { ElMessage } from 'element-plus'
import { handleSignout } from '@/utils/common'
import type { AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios'

const service = axios.create({
  timeout: 60000,
  withCredentials: true
} as any)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 文件下载
    if (response.headers['content-disposition'] && response.headers['content-disposition'].includes('attachment')) {
      return Promise.resolve(response)
    }
    if (response) {
      if (!response.data || ![0, '0', '00'].includes(response.data.code)) {
        ElMessage.error(response.data?.message || '网络异常，请重试')
        return Promise.reject(response)
      }
    }

    return Promise.resolve(response.data.data)
  },
  function (error: AxiosError) {
    if (error.response?.status === 401) {
      handleSignout()
      return Promise.reject(error)
    }
    ElMessage.error(error.message || '网络异常，请重试')
    return Promise.reject(error)
  }
)

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = window.localStorage.getItem('token')
    token && (config.headers.authorization = token)
    return config
  },
  function (error: AxiosError): Promise<AxiosError> {
    return Promise.reject(error)
  }
)

export default service
